import axios from "axios";
import {Message} from "element-ui";
import Storage from "@/js/storage.js"
import systemConfig from "@/system.config.js";
// import util from "@/js/util.js"

let axiosConfig = {
    baseURL: systemConfig.baseUrl ,
    // 超时时间
    timeout: 10*1000,
    headers: {
        'Content-Type': 'application/json; charset=UTF-8'
    },
    responseType: 'json'
}
let instance  = axios.create(axiosConfig);


instance.interceptors.request.use(config => {
    // 在发送请求之前做些什么
    if (systemConfig.whiteList.includes(config.url)) {
        return config;
    }
    config.headers.Authorization = 'Yanchen'+Storage.get("token");
    return config;
}, error => {
    return Promise.reject(error);
});


instance.interceptors.response.use(response => {
    // 对响应数据做点什么
    // console.log("response",response);
    switch (response.data.status) {
        case 200:
            return response;
        case 401:
            Message.error("登录超时，请重新登录");
            Storage.remove("token");
            setTimeout(() => {
                // util.indexPage(util.getCurrentRouter())
                window.location.href = "/login";
            }, 1000);
            break;
        case 500:
            Message.error(response.data.message);
            return Promise.reject(response);
        default:
            return response;
    }

}, error => {
    // 对响应错误做点什么
    console.log('err:' + error)
    let { message } = error;
    if (message === "Network Error") {
        message = "后端接口连接异常";
    } else if (message.includes("timeout")) {
        message = "系统接口请求超时";
    } else if (message.includes("Request failed with status code")) {
        message = `系统接口${message.substr(message.length - 3)}异常`;
    }
    Message.error(message);
    return Promise.reject(error)
});



export default instance
